package com.victorvieux.android.vlcmote;

import java.util.ArrayList;

import com.victorvieux.android.dialogs.volumeDiagManager;
import com.victorvieux.android.handlers.PlaylistHandler;
import com.victorvieux.android.handlers.StatusHandler;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import com.victorvieux.android.vlcmote.R;
import com.victorvieux.android.web.Communicate;
import com.victorvieux.android.web.play;
import com.victorvieux.android.web.stop;

public class main extends Activity {
	
	public static boolean playing = false;
	public static int currentId = 0;
	public static int textColor = 0;
	public static int textSize = 0;
	protected PowerManager.WakeLock mWakeLock = null; 

	private final Communicate _comm = Communicate.getInstance();
	private ProgressDialog wait = null;
	private StatusHandler sh = null;
	private PlaylistHandler ph = null;
	final Handler UIHandler = new Handler(); 
	final volumeDiagManager vdm = new volumeDiagManager(main.this);
	
	final Runnable r_updateStatus = new Runnable() {
        public void run() {
        	if (sh.isPlaying()) {
             	ImageButton playB = (ImageButton) findViewById(R.id.ButtonPlayPause);
             	playB.setBackgroundResource(R.drawable.i_pause); 
             	playing = true;
             }
        }
    };
    
    final Runnable r_updatePlaylist = new Runnable() {
        public void run() {
        		final ArrayList<leaf> playListItems = ph.getPlaylist();
        		ListView lv = (ListView)findViewById(R.id.list);
        		lv.setOnItemClickListener(new OnItemClickListener() {
					public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
						Communicate c = Communicate.getInstance();
						currentId = playListItems.get(pos).getId();
						c.send("pl_play", currentId);
						
						findViewById(R.id.ButtonPlayPause).setBackgroundResource(R.drawable.i_pause);
						main.playing = true;
					}
        		});
        		PlayListAdapter pa = new PlayListAdapter(getApplicationContext(), playListItems, main.textColor, main.textSize);
        		lv.setAdapter(pa);
        		lv.setSelection(ph.getCurrentPos());
        		currentId = ph.getCurrentId();
        }
    };
    
    final Runnable r_error = new Runnable() {
    	public void run() {
    		AlertDialog error = new AlertDialog.Builder(main.this).create();
        	error.setTitle(R.string.errorT);
        	error.setMessage(getText(R.string.errorM));
        	error.show();
        	error.setOnDismissListener(new OnDismissListener() {
        		public void onDismiss(DialogInterface dialog) {
        			main.this.finish();
        		}
        	});
    	}
    };
  
    final Runnable r_parse = new Runnable() {
    	public void run() {
    		wait = ProgressDialog.show(main.this, getText(R.string.diagT), getText(R.string.diagM), true, false);
		    wait.setOnCancelListener(new OnCancelListener() {
	    		public void onCancel(DialogInterface dialog) {
	    			main.this.finish();
	    		}
		    });
		    new Thread() {
	            public void run() {
	            	SharedPreferences settings = getSharedPreferences(com.victorvieux.android.vlcmote.conf.PREFS_NAME, 0);
	            	_comm.init(settings.getString("ip", "0.0.0.0"), settings.getString("port", "8080"));
	            	if (parseStatus() == false || parsePlaylist() == false) {
	            			wait.dismiss();
	            			UIHandler.post(r_error); 
	            	}
	            	else
	            		wait.dismiss();
	            }
			}.start();
    	}
    };
    
    final Runnable r_vol_up = new Runnable() {
    	public void run() {
    		_comm.send("volume&val=%2B50", 0);
    	}
    };
    
    final Runnable r_vol_down = new Runnable() {
    	public void run() {
    		_comm.send("volume&val=-50", 0);
    	}
    };
    
    @Override
    public boolean  onKeyDown  (int keyCode, KeyEvent event)  
    {
    	if (keyCode == 24)
    		UIHandler.post(r_vol_up);
    	else if (keyCode == 25)
    		UIHandler.post(r_vol_down);
    	else if (keyCode == 4)
    		this.finish();
    	else
    		return false;
    	return true;	
    }
    
    @Override
    public boolean  onKeyUp  (int keyCode, KeyEvent event)  
    {
    	Log.d("KEYUP", String.valueOf(keyCode));
    	if (keyCode == 24) {
    		vdm.showP();
    	}
    	else if (keyCode == 25){
    		vdm.showM();
    	}
    	else
    		return false;
    	return true;
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        setContentView(R.layout.main);

        ImageButton playB = (ImageButton) findViewById(R.id.ButtonPlayPause);
        ImageButton stopB = (ImageButton) findViewById(R.id.ButtonStop);
        ImageButton prevB = (ImageButton) findViewById(R.id.ButtonPrev);
        ImageButton nextB = (ImageButton) findViewById(R.id.ButtonNext);
        
        ImageButton seekMM = (ImageButton) findViewById(R.id.ButtonSMM);
        ImageButton seekM = (ImageButton) findViewById(R.id.ButtonSM);
        ImageButton seekP = (ImageButton) findViewById(R.id.ButtonSP);
        ImageButton seekPP = (ImageButton) findViewById(R.id.ButtonSPP);

        playB.setOnClickListener(new play());
        stopB.setOnClickListener(new stop(findViewById(R.id.ButtonPlayPause)));
        prevB.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { _comm.send("pl_previous", 0); } });
        nextB.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { _comm.send("pl_next", 0); } });

        seekMM.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { _comm.send("seek&val=-300", 0); } });
        seekM.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { _comm.send("seek&val=-30", 0); } });
        seekP.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { _comm.send("seek&val=%2B30", 0); } });
        seekPP.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { _comm.send("seek&val=%2B300", 0); } });

        startActivityForResult(new Intent(main.this, conf.class), 0);              
    }
    
    @Override
    public void onStop() {
    	super.onStop();
    }
    
    @Override
    public void onResume(){
    	super.onResume();
    	parsePreferences();
    	}
    
    
    @Override
    public void onDestroy() {
    	 if (this.mWakeLock != null && this.mWakeLock.isHeld())
    		this.mWakeLock.release();
         super.onDestroy();
    } 
    
    
	public void onConfigurationChanged(Configuration newConfig) {  
	         super.onConfigurationChanged(newConfig);  
	   
	}  

    @Override
    public void onActivityResult(int requestCode,  int resultCode, Intent data) {
    	switch (resultCode){
    	case conf.STATE_CONF_NOK:
    		AlertDialog alert = new AlertDialog.Builder(main.this).create();
			alert.setTitle(R.string.errorT);
			alert.setMessage(getText(R.string.ConfWifi).subSequence(0, getText(R.string.ConfWifi).length() - 1));
			alert.setButton(getText(R.string.ConfCancel), new DialogInterface.OnClickListener() {
    	      public void onClick(DialogInterface dialog, int which) {
    	    	  startActivityForResult(new Intent(main.this, conf.class), 0);
    	        } });
			alert.show();
			break;
    	case conf.STATE_CONF_OK:
    		r_parse.run();
    		break;
    	case prefs.STATE_PREFS:
    		//parsePreferences();
    		break;
    	}
    }
    
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu, menu);
    	return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	
    	case R.id.itemPlay:
    		UIHandler.post(r_parse);
    		break;
    		
    	case R.id.itemPref:
	    		Intent settingsActivity = new Intent(getBaseContext(), prefs.class);
	    		startActivityForResult(settingsActivity, 0 );
    		break;
    		
    	default:
			_comm.send("fullscreen", 0);
    	}
    	return true;
    }
    
    private boolean parseStatus() {
        sh = _comm.readStatus();
        if (sh == null)
        	return false;
        UIHandler.post(r_updateStatus); 
        return true;
    }
    
    private boolean parsePlaylist() {
    	ph = _comm.readPlaylist();
    	if (ph == null)
    		return false;
    	UIHandler.post(r_updatePlaylist);
    	return true;
    }  
    
    private void parsePreferences() {
    	Log.d("PARSE", "PARSE");
		View v = findViewById(R.id.Player2);

    	SharedPreferences settings = getSharedPreferences(conf.PREFS_NAME, 0);
        if(settings.getBoolean("checkboxSeek", false))
        	v.setVisibility(View.VISIBLE);
        else
    		v.setVisibility(View.INVISIBLE);

        if(settings.getBoolean("checkBoxNoSleep", false) && this.mWakeLock == null)  {
        	Log.d("SETWAKE", "SET");
        	 final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
             this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, conf.PREFS_NAME);
             this.mWakeLock.acquire(); 
        }
        
        main.textColor = settings.getInt("textColor", 0xffff4500);
        main.textSize = Integer.parseInt(settings.getString("sizePref", "16"));

    }
}